#include "onlinetileloader.h"
#include <QNetworkRequest>
#include <QUrl>

m_urlTpl::m_urlTpl(const QString &tpl, QObject *parent)
    : QObject(parent), m_tpl(tpl) {}

void m_urlTpl::fetch(int z, int x, int y) {
    QString url = m_tpl;
    url.replace("{x}", QString::number(x))
       .replace("{y}", QString::number(y))
       .replace("{z}", QString::number(z));

    QUrl qurl(url);
    QNetworkRequest req(qurl);
    qDebug() << "Request:" << url;
    QNetworkReply *reply = m_mgr.get(req);
    connect(reply, &QNetworkReply::finished, this, [this, z, x, y, reply] {
        if (reply->error() == QNetworkReply::NoError) {
            QPixmap pix;
            pix.loadFromData(reply->readAll());
            emit tileReady(z, x, y, pix);
        }
        reply->deleteLater();
    });
}

void m_urlTpl::onFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QPixmap pix;
        pix.loadFromData(reply->readAll());
        emit tileReady(reply->property("z").toInt(),
                       reply->property("x").toInt(),
                       reply->property("y").toInt(),
                       pix);
    }
    reply->deleteLater();
}
